import React, { useEffect, useRef, useState } from 'react'
import { Table, Modal, Button, Switch, Form, Input, Select } from 'antd';
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import axios from 'axios'
import UserForm from '../../../components/user-manage/userForm';
const { confirm } = Modal;
const { Option } = Select
export default function () {
  const [dataSource, setDataSource] = useState([])
  const [visible, setVisible] = useState(false);
  const [roleList, setroleList] = useState([])
  const [regionList, setregionList] = useState([])
  const [isUpdateVisible, setisUpdateVisible] = useState(false);
  const [isUpdateDisable, setisUpdateDisable] = useState(false)
  const [current, setcurent] = useState(null)
  const addFrom = useRef(null)
  const updateFrom = useRef(null)
  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    axios.get('/users?_expand=role').then(res => {
      // console.log(res)
      const list = res.data
      // console.log("----------",list.filter(item => item.username === username))

      // console.log("----------",list.filter(item => item.region === region || roleObj[item.roleId] === "editor"))
      setDataSource(roleObj[roleId] === "superadmin" ? list : [
        ...list.filter(item => item.username === username),
        ...list.filter(item => item.region === region && roleObj[item.roleId] === "editor")
      ])
    })
  }, [roleId, region, username])
  useEffect(() => {
    axios.get('/roles').then(res => {
      // console.log(res)
      setroleList(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get('/regions').then(res => {
      // console.log(res)
      setregionList(res.data)
    })
  }, [])
  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      key: 'region',
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        })),
        {
          text: "全球",
          value: "全球"
        }
      ],

      onFilter: (value, item) => {
        if (value === "全球") {
          return item.region === ""
        }
        return item.region === value
      },
      render: (key) => {
        return <b>{key == "" ? "全球" : key}</b>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      key: 'role',
      render: (role) => {
        return role?.roleName
      }
    },
    {
      title: '用户名',
      key: 'username',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      key: 'roleState',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <div>
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={() => handleChange(item)}
          ></Switch>
        </div>
      }
    },
    {
      title: "操作",
      key: 'caozuo',
      render: (key) => {
        return <div>
          <Button
            type="danger"
            shape="circle"
            onClick={() => { showConfirm(key) }}
            icon={<DeleteOutlined />}
            disabled={key.default}
          />
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            disabled={key.default}
            onClick={() => {
              handleUpadate(key)
            }} />
        </div>
      }
    }
  ]
  // switch更改用户状态
  const handleChange = (item) => {
    // console.log(item)
    item.roleState = !item.roleState
    setDataSource([...dataSource])
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
  }
  // 更新用户数据
  const handleUpadate = (item) => {
    setcurent(item)
    setTimeout(() => {
      setisUpdateVisible(true)
      if (item.roleId == 1) {
        // 禁用
        setisUpdateDisable(true)
      } else {
        // 取消禁用
        setisUpdateDisable(false)
      }
      // console.log(item)
      updateFrom.current.setFieldsValue(item)
    }, 100)
  }
  // 更新用户弹窗确认按钮
  const updateFromOk = () => {

    updateFrom.current.validateFields().then(value => {
      // console.log(value)
      setisUpdateVisible(false)
      setDataSource(dataSource.map(item => {
        if (item.id == current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      axios.patch(`/users/${current.id}`, value)
      // // post 后端，生成id再去设置datasousce，方便后面删除，更新操作
      // axios.post(`/users`,{
      //   ...value,
      //   "roleState": true,
      //   "default": false,
      // }).then(res=>{
      //   // // console.log(res)
      //   setDataSource([...dataSource,{
      //     ...res.data,
      //     role:roleList.filter(item=>item.id == value.roleId)[0]
      //   }])
      //   setVisible(false)
      //   // 重置文档
      //   addFrom.current.resetFields()
      // })
    }).catch(err => {
      // console.log(err)
    })
  }
  const showConfirm = (item) => {
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      onOk() {
        detaMethod(item)
      },
      onCancel() {
      },
    });
  }

  // 删除 当前页面同步状态 + 后端同步
  const detaMethod = (item) => {
    axios.delete(`/users/${item.id}`).then(res => {
      // console.log(res)
    })
    setDataSource(dataSource.filter(data => data.id !== item.id))
  }

  const onCreate = (values) => {
    // console.log('Received values of form: ', values);
    setVisible(false);
  };
  const addFromOk = () => {
    addFrom.current.validateFields().then(value => {
      // post 后端，生成id再去设置datasousce，方便后面删除，更新操作
      axios.post(`/users`, {
        ...value,
        "roleState": true,
        "default": false,
      }).then(res => {
        // // console.log(res)
        setDataSource([...dataSource, {
          ...res.data,
          role: roleList.filter(item => item.id == value.roleId)[0]
        }])
        setVisible(false)
        // 重置文档
        addFrom.current.resetFields()
      })
    }).catch(err => {
      // console.log(err)
    })
  }

  return (
    <div>
      <Button type="primary"
        onClick={() => {
          setVisible(true);
        }}
      >添加用户</Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        rowKey={(item) => item.id}
        pagination={
          { pageSize: 5 }
        } />;
      <Modal
        visible={visible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => setVisible(false)}
        onOk={() => {
          addFromOk()
        }}
      >
        <UserForm
          ref={addFrom}
          regionList={regionList}
          roleList={roleList}
        ></UserForm>
      </Modal>
      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => setisUpdateVisible(false)}
        onOk={() => {
          updateFromOk()
          setisUpdateVisible(!isUpdateDisable)
        }}
      >
        <UserForm
          ref={updateFrom}
          regionList={regionList}
          roleList={roleList}
          isUpdateDisable={isUpdateDisable}
          isUpdate={true}
        ></UserForm>
      </Modal>
    </div>
  )
}
